package com.components.cachewebview.utils

import android.text.TextUtils
import java.net.URL

object NetUtils {

    /**重新组装请求的header*/
    fun multimapToSingle(maps: Map<String, List<String>>?): MutableMap<String, String> {
        val sb = StringBuilder()
        val map: MutableMap<String, String> = mutableMapOf()
        maps?.entries?.forEach { it ->
            val values = it.value
            sb.delete(0, sb.length)
            if (values.isNotEmpty()) {
                values.forEach {
                    sb.append(it)
                    sb.append(";")
                }
            }
            if (sb.isNotEmpty()) {
                sb.deleteCharAt(sb.length - 1)
            }
            map[it.key] = sb.toString()
        }
        return map
    }

    fun getOriginUrl(referer: String): String {
        var ou = referer
        if (TextUtils.isEmpty(ou)) {
            return ""
        }
        try {
            val url = URL(ou)
            val port = url.port
            ou = url.protocol + "://" + url.host + if (port == -1) "" else ":$port"
        } catch (e: Exception) {
            ou = ""
        }
        return ou
    }

}